package org.tgcloud.group.service.task;

import cn.hutool.core.util.ObjUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.tgcloud.group.core.BeanUtil;
import org.tgcloud.group.core.RedisUtil;
import org.tgcloud.group.core.StringUtil;
import org.tgcloud.group.core.date.DateUtils;
import org.tgcloud.group.entity.*;
import org.tgcloud.group.repository.*;
import org.tgcloud.group.web.controller.dto.order.ChannelUserGoodListDTO;
import org.tgcloud.group.web.controller.dto.order.TreeOrderListDTO;
import org.tgcloud.group.web.controller.dto.sys.SysLabelValueListDTO;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author: zhy
 * @create: 2023-09-01 11:29
 * @description:
 */
@Component
public class OrderTask {

    @Autowired
    private MjOrderMapper orderMapper;

    @Autowired
    private MjUserOrderMapper userOrderMapper;

    @Autowired
    private SysLabelValueMapper sysLabelValueMapper;

    @Autowired
    private MjUserOrderGoodMapper userOrderGoodMapper;

    @Autowired
    private SendSubscribeMsgTask sendSubscribeMsgTask;

    @Autowired
    private MjUserOrderStatusMapper mjUserOrderStatusMapper;


    @Autowired
    private MjNormalUserMapper mjNormalUserMapper;

    private Boolean updateOrderBiddingStatus = false;

    @Scheduled(cron = "0 * * * * ?")
    public void doUpdateOrderBidding(){
        if(!updateOrderBiddingStatus && !RedisUtil.existKey("doUpdateOrderBidding")){
            RedisUtil.setCacheObject("doUpdateOrderBidding", "doUpdateOrderBidding", 10L, TimeUnit.SECONDS);
            updateOrderBiddingStatus = true;
            List<MjOrder> mjOrders = orderMapper.selectTaskList();
            Integer endUserId = null;
            if (mjOrders.size() > 0){
                for (MjOrder order : mjOrders){
                    //第一次竞价
                    if (order.getStatus() == 4){

                        String v4 = sysLabelValueMapper.selectValueBySysIdAndReadOne(4);
                        String v5 = sysLabelValueMapper.selectValueBySysIdAndReadOne(5);
                        //获取二次竞价结束时间的间隔时间段
                        List<SysLabelValueListDTO> sysLabelValueListDTOS = sysLabelValueMapper.selectListBySysLabelId(1, null,null);
                        SysLabelValueListDTO labelValueListDTO = sysLabelValueListDTOS.get(0);
                        String sysValueName = labelValueListDTO.getSysValueName();
                        BigDecimal endHour = new BigDecimal(sysValueName);
                        //第一次竞价结束
                        List<ChannelUserGoodListDTO> userGoodListDTOS = userOrderMapper.selectTaskListByOrderIdAndOrderType(order.getId(), (short) 2);
                        BigDecimal topPrice = BigDecimal.ZERO;
                        if (BeanUtil.isNullList(userGoodListDTOS)){
                            String[] pushUserIds = null;
                            if (order.getIsNextPush() == 2){
                                pushUserIds = order.getNextPushUserIds().split(",");
                            }
                            List<MjUserOrder> userOrders = userOrderMapper.selectTaskCheckMsgByOrderIdAndOrderType1(order.getId(), (short) 1, (short) 1,pushUserIds);
                            if (!BeanUtil.isNullList(userOrders)){
                                MjUserOrder userOrder = userOrders.get(0);
                                MjUserOrder mjUserOrder = new MjUserOrder();
                                BeanUtils.copyProperties(userOrder, mjUserOrder);
                                mjUserOrder.setOrderType((short) 2);
                                mjUserOrder.setRankNum(1);
                                mjUserOrder.setStatus((short) 2);
                                userOrderMapper.insertSelective(mjUserOrder);
                                List<MjUserOrderGood> mjUserOrderGoods = userOrderGoodMapper.selectMsgListByUserOrderId(userOrder.getId());
                                for (MjUserOrderGood good : mjUserOrderGoods){
                                    MjUserOrderGood orderGood = new MjUserOrderGood();
                                    BeanUtils.copyProperties(good, orderGood);
                                    orderGood.setUserOrderId(mjUserOrder.getId());
                                    userOrderGoodMapper.insertSelective(orderGood);
                                }
                                topPrice = mjUserOrder.getTotalPrice();
                                userGoodListDTOS = userOrderMapper.selectTaskListByOrderIdAndOrderType(order.getId(), (short) 2);
                                sendSubscribeMsgTask.doPushMap(mjUserOrder.getUserId().toString(), order.getOrderKey(), order.getBrands(), "竞价结束", "您已竞价成功", null);
                            }
                        }else {
                            for (int i=0;i<userGoodListDTOS.size();i++){
                                ChannelUserGoodListDTO dto = userGoodListDTOS.get(i);
                                if(dto.getTotalPrice().compareTo(topPrice) > 0){
                                    topPrice = dto.getTotalPrice();
                                }
                                short status = 2;
                                //百分比下最低金额
                                BigDecimal decimal = topPrice.subtract(topPrice.multiply(BigDecimal.valueOf(Long.valueOf(v4))).divide(BigDecimal.valueOf(100L), 2, BigDecimal.ROUND_HALF_UP));
                                //固定金额下最低金额
                                BigDecimal subtract = topPrice.subtract(BigDecimal.valueOf(Long.valueOf(v5)));
                                if (decimal.compareTo(dto.getTotalPrice()) > -1){
                                    if (subtract.compareTo(dto.getTotalPrice()) > -1){
                                        status = 3;
                                    }else {
                                        status = 2;
                                    }
                                }else {
                                    status = 2;
                                }
                                // 第一次竞价出现第二名并且第二名是竞价失败的时候，把第二名改成竞价成功
                                if (i + 1 == 2 && status == 3 && dto.getTotalPrice().compareTo(BigDecimal.ZERO) > 0){
                                    status = 2;
                                }
                                userOrderMapper.updateRankAndStatusByUserOrderId(dto.getUserOrderId(), i+1, status);
                                //todo   //如果渠道没报价---已结束
                                List<Integer> list1 = new ArrayList<>();
                                List<Integer> list2 = new ArrayList<>();
                                if (StringUtil.isNotBlank(order.getBiddingPushChannelUserIds()) && (StringUtil.isNotBlank(order.getBiddingPushChannelUserIds()))){
                                    list1 = Arrays.stream(order.getBiddingPushChannelUserIds().split(","))
                                            .map(Integer::parseInt)
                                            .collect(Collectors.toList());
                                }
                                if (StringUtil.isNotBlank(order.getBiddingPushChannelUserIds()) && (StringUtil.isNotBlank(order.getBiddingPushChannelUserIds()))){
                                    list2 = Arrays.stream(order.getBiddingFirstUserIds().split(","))
                                            .map(Integer::parseInt)
                                            .collect(Collectors.toList());
                                }
                                Set<Integer> set2 = new HashSet<>(list2);
                                List<Integer> differenceList = new ArrayList<>();
                                for (int num : list1) {
                                    if (!set2.contains(num)) {
                                        differenceList.add(num);
                                    }
                                }
                                //todo   //如果渠道没报价---已结束
                                for (Integer differenceId : differenceList) {
                                    MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(differenceId, order.getId());
                                    if (isHaveObj != null) {
                                        MjUserOrderStatus orderStatusObj = new MjUserOrderStatus();
                                        orderStatusObj.setOrderStatus(78);
                                        orderStatusObj.setUpdateTime(new Date());
                                        orderStatusObj.setId(isHaveObj.getId());
                                        mjUserOrderStatusMapper.updateByPrimaryKeySelective(orderStatusObj);
                                    }
                                }
                                // 一次报价过低被淘汰--已结束，
                                if (status == 3){
                                    MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(dto.getUserId(), order.getId());
                                    if (isHaveObj != null) {
                                        MjUserOrderStatus orderStatusObj = new MjUserOrderStatus();
                                        orderStatusObj.setOrderStatus(78);
                                        orderStatusObj.setUpdateTime(new Date());
                                        orderStatusObj.setId(isHaveObj.getId());
                                        mjUserOrderStatusMapper.updateByPrimaryKeySelective(orderStatusObj);
                                    }
                                }
                                if (status == 2){
                                    //渠道：由一次竞价进入二次竞价，正常进入
                                    MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(dto.getUserId(), order.getId());
                                    if (isHaveObj != null) {
                                        MjUserOrderStatus orderStatusObj = new MjUserOrderStatus();
                                        orderStatusObj.setOrderStatus(76);
                                        orderStatusObj.setUpdateTime(new Date());
                                        orderStatusObj.setId(isHaveObj.getId());
                                        mjUserOrderStatusMapper.updateByPrimaryKeySelective(orderStatusObj);
                                    }
                                }
                                //开拓者统一二次竞价：
                                for (String pushId : order.getBiddingPushUserIds().split(",")) {
                                    MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(Integer.valueOf(pushId), order.getId());
                                    //开拓者已结束
                                    if (isHaveObj != null) {
                                        MjUserOrderStatus orderStatusObj = new MjUserOrderStatus();
                                        orderStatusObj.setOrderStatus(87);
                                        orderStatusObj.setUpdateTime(new Date());
                                        orderStatusObj.setId(isHaveObj.getId());
                                        mjUserOrderStatusMapper.updateByPrimaryKeySelective(orderStatusObj);
                                    }
                                }

                                String value3 = "第一次竞价结束";
                                if (userGoodListDTOS.size() == 1){
                                    value3 = "竞价结束";
                                }
                                String value4 = "您已竞价成功，请准备第二次竞价";
                                if (userGoodListDTOS.size() == 1){
                                    value4 = "您已竞价成功，请准备货品进行发货";
                                }else if (status == 3){
                                    value4 = "竞价失败";
                                }
                                sendSubscribeMsgTask.doPushMap(dto.getUserId().toString(), order.getOrderKey(), order.getBrands(), value3, value4, null);

                            }
                        }
                        //一次竞价到二次竞价结束时间段
                        if (!BeanUtil.isNullList(userGoodListDTOS)){
                            order.setBiddingTwoTimeSlot(endHour);
                            order.setBiddingOneFirstPrice(topPrice);
                            order.setStatus((short) 5);
                        }
                        //判断第一次竞价的订单数量，如果只有1条，就直接订单结束
                        if (!BeanUtil.isNullList(userGoodListDTOS) && userGoodListDTOS.size() == 1){
                            endUserId = userGoodListDTOS.get(0).getUserId();
                            order.setStatus((short) 7);
                            order.setEndTime(new Date());
                            order.setLastUserId(endUserId);
                            //开拓者结束
                            for (String pushId : order.getBiddingPushUserIds().split(",")) {
                                MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(Integer.valueOf(pushId), order.getId());
                                //开拓者已结束
                                if (isHaveObj != null) {
                                    MjUserOrderStatus orderStatusObj = new MjUserOrderStatus();
                                    orderStatusObj.setOrderStatus(88);
                                    orderStatusObj.setUpdateTime(new Date());
                                    orderStatusObj.setId(isHaveObj.getId());
                                    mjUserOrderStatusMapper.updateByPrimaryKeySelective(orderStatusObj);
                                }
                            }
                            //开拓者分为已结束和已中标
                            //渠道分为已拿下未拿下已结束
                            if (StringUtil.isNotBlank(order.getBiddingPushChannelUserIds())){
                                for (String pushId : order.getBiddingPushChannelUserIds().split(",")) {
                                    if (pushId.equals(endUserId.toString())){
                                        //渠道拿下
                                        MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(Integer.valueOf(pushId), order.getId());
                                        if (isHaveObj != null) {
                                            MjUserOrderStatus orderStatusObj = new MjUserOrderStatus();
                                            orderStatusObj.setOrderStatus(93);
                                            orderStatusObj.setUpdateTime(new Date());
                                            orderStatusObj.setId(isHaveObj.getId());
                                            mjUserOrderStatusMapper.updateByPrimaryKeySelective(orderStatusObj);
                                        }
                                        //开拓者拿下
                                        MjNormalUser mjNormalUser = mjNormalUserMapper.selectByPrimaryKey(Integer.valueOf(pushId));
                                        MjUserOrderStatus isHaveObj2 = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(mjNormalUser.getPushUserId(), order.getId());
                                        if (isHaveObj2 != null) {
                                            MjUserOrderStatus orderStatusObj2 = new MjUserOrderStatus();
                                            orderStatusObj2.setOrderStatus(99);
                                            orderStatusObj2.setUpdateTime(new Date());
                                            orderStatusObj2.setId(isHaveObj2.getId());
                                            mjUserOrderStatusMapper.updateByPrimaryKeySelective(orderStatusObj2);
                                        }
                                    } else {
                                        //渠道已结束
                                        MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(Integer.valueOf(pushId), order.getId());
                                        if (isHaveObj != null) {
                                            MjUserOrderStatus orderStatusObj = new MjUserOrderStatus();
                                            orderStatusObj.setOrderStatus(78);
                                            orderStatusObj.setUpdateTime(new Date());
                                            orderStatusObj.setId(isHaveObj.getId());
                                            mjUserOrderStatusMapper.updateByPrimaryKeySelective(orderStatusObj);
                                        }
                                    }
                                }
                            }
                        }
                        //如果一次报价中因价格差距过大，只剩下一个有效报价，那么直接订单结束
                        Integer hasCountNum = userOrderMapper.selectCountByOrderIdAndOrderType(order.getId(), (short) 2);
                        if (hasCountNum != null && hasCountNum == 1){
                            endUserId = userOrderMapper.selectFirstNumByOrderIdAndOrderType(order.getId(), (short) 2);
                            order.setStatus((short) 7);
                            order.setEndTime(new Date());
                            order.setLastUserId(endUserId);
                            //开拓者结束
                            for (String pushId : order.getBiddingPushUserIds().split(",")) {
                                MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(Integer.valueOf(pushId), order.getId());
                                //开拓者已结束
                                if (isHaveObj != null) {
                                    MjUserOrderStatus orderStatusObj = new MjUserOrderStatus();
                                    orderStatusObj.setOrderStatus(88);
                                    orderStatusObj.setUpdateTime(new Date());
                                    orderStatusObj.setId(isHaveObj.getId());
                                    mjUserOrderStatusMapper.updateByPrimaryKeySelective(orderStatusObj);
                                }
                            }
                            //开拓者分为已结束和已中标
                            //渠道分为已拿下未拿下已结束
                            if (StringUtil.isNotBlank(order.getBiddingPushChannelUserIds())){
                                for (String pushId : order.getBiddingPushChannelUserIds().split(",")) {
                                    if (pushId.equals(endUserId.toString())){
                                        //渠道拿下
                                        MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(Integer.valueOf(pushId), order.getId());
                                        if (isHaveObj != null) {
                                            MjUserOrderStatus orderStatusObj = new MjUserOrderStatus();
                                            orderStatusObj.setOrderStatus(93);
                                            orderStatusObj.setUpdateTime(new Date());
                                            orderStatusObj.setId(isHaveObj.getId());
                                            mjUserOrderStatusMapper.updateByPrimaryKeySelective(orderStatusObj);
                                        }
                                        //开拓者拿下
                                        MjNormalUser mjNormalUser = mjNormalUserMapper.selectByPrimaryKey(Integer.valueOf(pushId));
                                        MjUserOrderStatus isHaveObj2 = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(mjNormalUser.getPushUserId(), order.getId());
                                        if (isHaveObj2 != null) {
                                            MjUserOrderStatus orderStatusObj2 = new MjUserOrderStatus();
                                            orderStatusObj2.setOrderStatus(99);
                                            orderStatusObj2.setUpdateTime(new Date());
                                            orderStatusObj2.setId(isHaveObj2.getId());
                                            mjUserOrderStatusMapper.updateByPrimaryKeySelective(orderStatusObj2);
                                        }
                                    } else {
                                        //渠道已结束
                                        MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(Integer.valueOf(pushId), order.getId());
                                        if (isHaveObj != null) {
                                            MjUserOrderStatus orderStatusObj = new MjUserOrderStatus();
                                            orderStatusObj.setOrderStatus(78);
                                            orderStatusObj.setUpdateTime(new Date());
                                            orderStatusObj.setId(isHaveObj.getId());
                                            mjUserOrderStatusMapper.updateByPrimaryKeySelective(orderStatusObj);
                                        }
                                    }
                                }
                            }
                        }
                        orderMapper.updateByPrimaryKeySelective(order);
                        if (order.getStatus() == 7){
                            //找到父订单，查看父订单的子表单是否全部已完成
                            if (ObjUtil.isNotNull(order.getParentId())){
                                if (ObjUtil.isNotNull(order.getEndTime())){
                                    //修改父订单结束时间
                                    orderMapper.updateEndTime(order.getParentId(),order.getEndTime());
                                }
                                TreeOrderListDTO hasChildNoComplete = orderMapper.selectChildNoComplete(order.getParentId());
                                if (ObjUtil.isEmpty(hasChildNoComplete)){
                                    orderMapper.updateStatusByOrderId(order.getParentId(),(short) 7);
                                    orderMapper.updateEndTime(order.getParentId(),new Date());
                                    MjOrder parentOrder = orderMapper.selectByPrimaryKey(order.getParentId());
                                    //父订单的开拓者为已结束状态
                                    Set<Integer> allPushUserIds = getAllPushUserIds(parentOrder.getPushUserIds(), parentOrder.getNextPushUserIds(), parentOrder.getTransferUserIds(),parentOrder.getBiddingPushUserIds());
                                    for (Integer pushUserId : allPushUserIds) {
                                        MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(pushUserId, parentOrder.getId());
                                        if (isHaveObj != null){
                                            MjUserOrderStatus orderStatusObj = new MjUserOrderStatus();
                                            orderStatusObj.setOrderStatus(88);
                                            orderStatusObj.setUpdateTime(new Date());
                                            orderStatusObj.setId(isHaveObj.getId());
                                            mjUserOrderStatusMapper.updateByPrimaryKeySelective(orderStatusObj);
                                        }
                                    }
                                    //渠道为已结束状态------但是小程序渠道看不到父表单
                                    if (StringUtil.isNotBlank(parentOrder.getPushChannelUserIds())){
                                        for (String channelId : parentOrder.getPushChannelUserIds().split(",")) {
                                            MjUserOrderStatus mjUserOrderStatus = new MjUserOrderStatus();
                                            mjUserOrderStatus.setOrderStatus(78);
                                            mjUserOrderStatus.setUpdateTime(new Date());
                                            MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(Integer.valueOf(channelId), parentOrder.getId());
                                            if (isHaveObj != null){
                                                mjUserOrderStatus.setId(isHaveObj.getId());
                                                mjUserOrderStatusMapper.updateByPrimaryKeySelective(mjUserOrderStatus);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }else if (order.getStatus() == 5){
                        long l = order.getBiddingTwoTimeSlot().multiply(new BigDecimal(3600)).multiply(new BigDecimal(1000)).longValue();
                        Long t = order.getBiddingOneEndTime().getTime() + l;
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
                        String nowTime = sdf.format(new Date());
                        String tTime = sdf.format(new Date(t));
                        if (Long.valueOf(nowTime) > Long.valueOf(tTime)){
                            // 判断第一次竞价结束的第一名是否参与了第二次报价，没有参与就默认添加第二次报价
                            Integer firstUserId = userOrderMapper.selectUserIdByOrderIdAndOrderTypeAndRankNum(order.getId(), (short) 2, 1);
                            // 查询第二次报价中，是否存在第一次报价的第一名，没有就默认添加第二次报价数据
                            MjUserOrder mjUserOrder = userOrderMapper.selectMsgByOrderIdAndOrderTypeAndUserId(order.getId(), (short) 3, firstUserId);
                            if (null == mjUserOrder){
                                List<MjUserOrder> userOrders = userOrderMapper.selectTaskListByOrderIdAndUserIdAndOrderType(order.getId(), (short) 2, firstUserId);
                                for (MjUserOrder userOrder : userOrders){
                                    List<MjUserOrderGood> mjUserOrderGoods = userOrderGoodMapper.selectMsgListByUserOrderId(userOrder.getId());
                                    userOrder.setId(null);
                                    userOrder.setStatus((short) 1);
                                    userOrder.setOrderType((short) 3);
                                    userOrder.setRankNum(null);
                                    userOrder.setCreateTime(userOrder.getCreateTime());
                                    userOrderMapper.insertSelective(userOrder);
                                    for (MjUserOrderGood userOrderGood : mjUserOrderGoods){
                                        userOrderGood.setId(null);
                                        userOrderGood.setUserOrderId(userOrder.getId());
                                        userOrderGoodMapper.insertSelective(userOrderGood);
                                    }
                                }
                            }
                            //第二次竞价结束
                            List<ChannelUserGoodListDTO> userGoodListDTOS = userOrderMapper.selectListByOrderIdAndOrderType(order.getId(), (short) 3, null);
                            BigDecimal topPrice = BigDecimal.ZERO;
                            if (!BeanUtil.isNullList(userGoodListDTOS) && userGoodListDTOS.size() > 0){
                                //开拓者已结束
                                for (String pushId : order.getBiddingPushUserIds().split(",")) {
                                    MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(Integer.valueOf(pushId), order.getId());
                                    //开拓者已结束
                                    if (isHaveObj != null) {
                                        MjUserOrderStatus orderStatusObj = new MjUserOrderStatus();
                                        orderStatusObj.setOrderStatus(88);
                                        orderStatusObj.setUpdateTime(new Date());
                                        orderStatusObj.setId(isHaveObj.getId());
                                        mjUserOrderStatusMapper.updateByPrimaryKeySelective(orderStatusObj);
                                    }
                                }
                                for (int i=0;i<userGoodListDTOS.size();i++){
                                    ChannelUserGoodListDTO dto = userGoodListDTOS.get(i);
                                    if(dto.getTotalPrice().compareTo(topPrice) > 0){
                                        topPrice = dto.getTotalPrice();
                                        endUserId = dto.getUserId();
                                    }
                                    userOrderMapper.updateRankByUserOrderId(dto.getUserOrderId(), i+1);
                                    String value3 = "第二次竞价结束";
                                    if (userGoodListDTOS.size() == 1){
                                        value3 = "竞价结束";
                                    }
                                    String value4 = "您已竞价成功，请准备货品进行发货";
                                    if (userGoodListDTOS.size() == 1){
                                        value4 = "您已竞价成功，请准备货品进行发货";
                                    }else if (i != 0){
                                        value4 = "竞价失败";
                                    }
                                    if (i == 0){
                                        Integer lastUserId = userGoodListDTOS.get(i).getUserId();
                                        //渠道拿下
                                        MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(lastUserId, order.getId());
                                        if (isHaveObj != null) {
                                            MjUserOrderStatus orderStatusObj = new MjUserOrderStatus();
                                            orderStatusObj.setOrderStatus(93);
                                            orderStatusObj.setUpdateTime(new Date());
                                            orderStatusObj.setId(isHaveObj.getId());
                                            mjUserOrderStatusMapper.updateByPrimaryKeySelective(orderStatusObj);
                                        }
                                        //开拓者拿下
                                        MjNormalUser mjNormalUser = mjNormalUserMapper.selectByPrimaryKey(lastUserId);
                                        MjUserOrderStatus isHaveObj2 = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(mjNormalUser.getPushUserId(), order.getId());
                                        if (isHaveObj2 != null) {
                                            MjUserOrderStatus orderStatusObj2 = new MjUserOrderStatus();
                                            orderStatusObj2.setOrderStatus(99);
                                            orderStatusObj2.setUpdateTime(new Date());
                                            orderStatusObj2.setId(isHaveObj2.getId());
                                            mjUserOrderStatusMapper.updateByPrimaryKeySelective(orderStatusObj2);
                                        }
                                    } else {
                                        //渠道未中标
                                        Integer userId = userGoodListDTOS.get(i).getUserId();
                                        MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(userId, order.getId());
                                        if (isHaveObj != null) {
                                            MjUserOrderStatus orderStatusObj = new MjUserOrderStatus();
                                            orderStatusObj.setOrderStatus(92);
                                            orderStatusObj.setUpdateTime(new Date());
                                            orderStatusObj.setId(isHaveObj.getId());
                                            mjUserOrderStatusMapper.updateByPrimaryKeySelective(orderStatusObj);
                                        }
                                    }
                                    sendSubscribeMsgTask.doPushMap(dto.getUserId().toString(), order.getOrderKey(), order.getBrands(), value3, value4, null);
                                }

                            }else {
                                ChannelUserGoodListDTO goodListDTO = userOrderMapper.selectTopMsgByOrderIdAndOrderType(order.getId(), (short) 2);
                                topPrice = goodListDTO.getTotalPrice();
                                endUserId = goodListDTO.getUserId();
                                String value3 = "竞价结束";
                                String value4 = "您已竞价成功，请准备货品进行发货";
                                sendSubscribeMsgTask.doPushMap(goodListDTO.getUserId().toString(), order.getOrderKey(), order.getBrands(), value3, value4, null);
                            }

                            order.setLastUserId(endUserId);
                            order.setBiddingTwoTopPrice(topPrice);
                            order.setStatus((short) 7);
                            order.setEndTime(new Date());
                            orderMapper.updateByPrimaryKeySelective(order);
                            if (order.getStatus() == 7){
                                //找到父订单，查看父订单的子表单是否全部已完成
                                if (ObjUtil.isNotNull(order.getParentId())){
                                    TreeOrderListDTO hasChildNoComplete = orderMapper.selectChildNoComplete(order.getParentId());
                                    if (ObjUtil.isNotNull(order.getEndTime())){
                                        //修改父订单结束时间
                                        orderMapper.updateEndTime(order.getParentId(),order.getEndTime());
                                    }
                                    if (ObjUtil.isEmpty(hasChildNoComplete)){
                                        orderMapper.updateStatusByOrderId(order.getParentId(),(short) 7);
                                        orderMapper.updateEndTime(order.getParentId(),new Date());
                                        MjOrder parentOrder = orderMapper.selectByPrimaryKey(order.getParentId());
                                        //父订单的开拓者为已结束状态
                                        Set<Integer> allPushUserIds = getAllPushUserIds(parentOrder.getPushUserIds(), parentOrder.getNextPushUserIds(), parentOrder.getTransferUserIds(),parentOrder.getBiddingPushUserIds());
                                        for (Integer pushUserId : allPushUserIds) {
                                            MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(pushUserId, parentOrder.getId());
                                            if (isHaveObj != null){
                                                MjUserOrderStatus orderStatusObj = new MjUserOrderStatus();
                                                orderStatusObj.setOrderStatus(88);
                                                orderStatusObj.setUpdateTime(new Date());
                                                orderStatusObj.setId(isHaveObj.getId());
                                                mjUserOrderStatusMapper.updateByPrimaryKeySelective(orderStatusObj);
                                            }
                                        }
                                        //渠道为已结束状态------但是小程序渠道看不到父表单
                                        if (StringUtil.isNotBlank(parentOrder.getPushChannelUserIds())){
                                            for (String channelId : parentOrder.getPushChannelUserIds().split(",")) {
                                                MjUserOrderStatus mjUserOrderStatus = new MjUserOrderStatus();
                                                mjUserOrderStatus.setOrderStatus(78);
                                                mjUserOrderStatus.setUpdateTime(new Date());
                                                MjUserOrderStatus isHaveObj = mjUserOrderStatusMapper.selectObjByUserIdAndOrderId(Integer.valueOf(channelId), parentOrder.getId());
                                                if (isHaveObj != null){
                                                    mjUserOrderStatus.setId(isHaveObj.getId());
                                                    mjUserOrderStatusMapper.updateByPrimaryKeySelective(mjUserOrderStatus);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            //如果渠道二次竞价没有发起挑战，为已结束
                            List<MjUserOrderStatus> userOrderStatusList = mjUserOrderStatusMapper.selectByOrderIdAndStatus(order.getId(), 76);
                            if (userOrderStatusList != null && userOrderStatusList.size()>0){
                                for (MjUserOrderStatus orderStatusObj : userOrderStatusList) {
                                    orderStatusObj.setUpdateTime(new Date());
                                    orderStatusObj.setOrderStatus(92);
                                    mjUserOrderStatusMapper.updateByPrimaryKeySelective(orderStatusObj);

                                }
                            }
                        }

                    }
                }
            }
            updateOrderBiddingStatus = false;
        }
    }



    /**
     * @author: zhy
     * @description: 每天10点运行一次，进行通知长时间未处理的订单，只需要推送给发布者和开拓者。渠道商不需要推送
     * @create: 2023年10月12日 09:31
     * @return
     */
    private Boolean updateLongTimeNoUpdateStatus = false;

//    @Scheduled(cron = "0 10 * * * ?")
    public void doSendLongTimeNoUpdateOrder(){
        if (!updateLongTimeNoUpdateStatus){
            RedisUtil.setCacheObject("doSendLongTimeNoUpdateOrder", "doSendLongTimeNoUpdateOrder");
            updateLongTimeNoUpdateStatus = true;
            List<SysLabelValueListDTO> sysLabelValueListDTOS = sysLabelValueMapper.selectListBySysLabelId(15, null,null);
            for (SysLabelValueListDTO dto : sysLabelValueListDTOS){
                String time = dto.getSysValueName();
                String desc = "此项目已提交表单" + time + "天，请跟进";
                Long t = new Date().getTime() + (Long.valueOf(time) * 24 * 60 * 60 * 1000);
                List<MjOrder> orders = orderMapper.selectNeedUpdateTask(t);
                if (!BeanUtil.isNullList(orders)){
                    for (MjOrder order : orders){
                        if (order.getIsPush() == 1){
                            // 订单刚创建，待推送给开拓者
                            sendSubscribeMsgTask.doPushTimeOutMap(order.getCreateUserId().toString(), order.getBrands(), order.getOrderKey(), desc, "CdyMJ4XLi-8_Ls3FswgKfYZmbThOoFook0vW99Rgbt0");
                        }else if(order.getIsNextPush() == 1){
                            // 没有进行过转推的订单
                            if (order.getStatus() == 1 || order.getStatus() == 2){
                                sendSubscribeMsgTask.doPushTimeOutMap(order.getPushUserIds(), order.getBrands(), order.getOrderKey(), desc, "CdyMJ4XLi-8_Ls3FswgKfYZmbThOoFook0vW99Rgbt0");
                            }else if (order.getStatus() == 3){
                                sendSubscribeMsgTask.doPushTimeOutMap(order.getCreateUserId().toString(), order.getBrands(), order.getOrderKey(), desc, "CdyMJ4XLi-8_Ls3FswgKfYZmbThOoFook0vW99Rgbt0");
                            }else if (order.getStatus() == 4){
                                sendSubscribeMsgTask.doPushTimeOutMap(order.getPushUserIds(), order.getBrands(), order.getOrderKey(), desc, "CdyMJ4XLi-8_Ls3FswgKfYZmbThOoFook0vW99Rgbt0");
                            }
                        }else if (order.getIsNextPush() == 2){
                            // 进行过转推的订单
                            if (order.getStatus() == 1 || order.getStatus() == 2){
                                sendSubscribeMsgTask.doPushTimeOutMap(order.getNextPushUserIds(), order.getBrands(), order.getOrderKey(), desc, "CdyMJ4XLi-8_Ls3FswgKfYZmbThOoFook0vW99Rgbt0");
                            }else if (order.getStatus() == 3){
                                sendSubscribeMsgTask.doPushTimeOutMap(order.getCreateUserId().toString(), order.getBrands(), order.getOrderKey(), desc, "CdyMJ4XLi-8_Ls3FswgKfYZmbThOoFook0vW99Rgbt0");
                            }else if (order.getStatus() == 4){
                                sendSubscribeMsgTask.doPushTimeOutMap(order.getNextPushUserIds(), order.getBrands(), order.getOrderKey(), desc, "CdyMJ4XLi-8_Ls3FswgKfYZmbThOoFook0vW99Rgbt0");
                            }
                        }
                    }
                }
            }
            updateLongTimeNoUpdateStatus = false;
        }
    }


    /**
     * @author: ljl
     * @description: 每天0点运行一次，长时间未处理，设置为超时
     * 你好
     */
    private Boolean checkOrderTimeOutFlag = false;
//    @Scheduled(cron = "0 * * * * ?")
    @Scheduled(cron = "0 0 0 * * ?")
    public void doCheckOrderTimeOut(){
        if (RedisUtil.existKey("doCheckOrderTimeOut")){
            return;
        }
        RedisUtil.setCacheObject("doCheckOrderTimeOut", "doCheckOrderTimeOut", 60L, TimeUnit.SECONDS);
        if (!checkOrderTimeOutFlag){
            checkOrderTimeOutFlag = true;
            // 获取当前时间（以指定时区为例，如"Asia/Shanghai"）
            ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Asia/Shanghai"));
            // 往前推两个月
            ZonedDateTime twoMonthsAgo = now.minusMonths(2);
            // 直接将ZonedDateTime转换为Date类型
            Date twoMonthsAgoDate = Date.from(twoMonthsAgo.toInstant());
            // 数据库进行判断
            List<MjOrder> orderList = orderMapper.selectTimeOutList(twoMonthsAgoDate);
            if (orderList != null && !orderList.isEmpty()){
                for (MjOrder order : orderList) {
                    orderMapper.updateIsTimeOut(order.getId(), (short) 2);
                }
            }
        }
    }

    public  Set<Integer> getAllPushUserIds(String pushUserIds,String nextPushUserIds,String transferUserIds,String biddingPushUserIds) {
        Set<Integer> userIdSet= new HashSet<>();
        if (StringUtil.isNotBlank(pushUserIds)){
            List<Integer> str1 = Arrays.stream(pushUserIds.split(","))
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
            userIdSet.addAll(str1);
        }

        if (StringUtil.isNotBlank(nextPushUserIds)){
            List<Integer> str2 = Arrays.stream(nextPushUserIds.split(","))
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
            userIdSet.addAll(str2);
        }
        if (StringUtil.isNotBlank(transferUserIds)){
            List<Integer> str3 = Arrays.stream(transferUserIds.split(","))
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
            userIdSet.addAll(str3);
        }
        if (StringUtil.isNotBlank(biddingPushUserIds)){
            List<Integer> str4 = Arrays.stream(biddingPushUserIds.split(","))
                    .map(Integer::parseInt)
                    .collect(Collectors.toList());
            userIdSet.addAll(str4);
        }
        return userIdSet;
    }

    @Autowired
    private DateUtils dateUtils;

    // 每隔10分钟执行一次
    @Scheduled(fixedDelay = 600000)
    public void doUpdateOrderPushHandleDiffTime(){
        String types = "1";
        String[] split = types.split(",");
        List<MjOrder> mjOrders = orderMapper.selectAllPushSureCheckTypeList(split);
        for (MjOrder order : mjOrders){
            Long startTime = order.getPushTime() != null ? order.getPushTime().getTime() : order.getCreateTime().getTime();
            Long endTime = new Date().getTime();
            Long holidayNumByTime = dateUtils.getHolidayNumByTime(startTime, endTime);
            orderMapper.updatePushUserHandleDiffTimeById(holidayNumByTime, order.getId());
        }
    }


    // 每天执行一次，把父表单的状态进行修改，如果子表单的状态全是已结束，那么父表单的状态也改为已结束
    @Scheduled(cron = "0 2 * * * ?")
    public void doUpdateParentOrderUserStatus(){
        String key = "doHasUpdateParentOrderIds";
        String ids = RedisUtil.getCacheObject(key);
        String[] idList = StringUtil.isNotBlank(ids) ? ids.split(",") : null;
        List<MjOrder> mjOrders = orderMapper.selectAllParentOrderList();
        if (!BeanUtil.isNullList(mjOrders)){
            for (MjOrder order : mjOrders){
                boolean hasAllEnd = true;
                List<MjOrder> subOrderList = orderMapper.selectSubOrderByParentOrderId(order.getId());
                if (!BeanUtil.isNullList(subOrderList)){
                    for (MjOrder subOrder : subOrderList){
                        if (subOrder.getStatus() >= 7){
                        }else {
                            hasAllEnd = false;
                        }
                    }
                }else {
                    hasAllEnd = false;
                }
                if (hasAllEnd){
                    List<MjUserOrderStatus> userOrderStatusList = mjUserOrderStatusMapper.selectAllListByOrderId(order.getId());
                    if (!BeanUtil.isNullList(userOrderStatusList)){
                        for (MjUserOrderStatus userOrderStatus : userOrderStatusList){
                            MjNormalUser normalUser = mjNormalUserMapper.selectByPrimaryKey(userOrderStatus.getUserId());
                            if (normalUser != null && normalUser.getUserType() == 1){
                                if (userOrderStatus.getOrderStatus() < 78){
                                    mjUserOrderStatusMapper.updateOrderStatusByOrderIdAndUserId(order.getId(), userOrderStatus.getUserId(), 78);
                                }
                            }
                            if (normalUser != null && normalUser.getUserType() == 2){
                                if (userOrderStatus.getOrderStatus() < 88){
                                    mjUserOrderStatusMapper.updateOrderStatusByOrderIdAndUserId(order.getId(), userOrderStatus.getUserId(), 88);
                                }
                            }
                        }
                    }
                    if (idList == null){
                        ids = (StringUtil.isNotBlank(ids) ? (ids + ",") : "") + order.getId();
                    }
                    if (idList != null && idList.length > 0){
                        if (!Arrays.asList(idList).contains(order.getId().toString())){
                            ids = (StringUtil.isNotBlank(ids) ? (ids + ",") : "") + order.getId();
                        }
                    }
                }
            }
            RedisUtil.setCacheObject(key, ids);
        }
    }

    // 每天晚上10点20分开始执行
    @Scheduled(cron = "0 20 22 * * ?")
    public void doUpdateOtherUserOrderStatusTask(){
        // 已结束订单中，渠道商状态处于核价中、竞价中的，设置已结束
        List<Integer> statusList = Stream.of(71, 72, 73, 74, 75, 76)
                .collect(Collectors.toList());
        List<MjUserOrderStatus> userOrderStatusList = mjUserOrderStatusMapper.selectTaskListByStatusList(statusList);
        Map<Integer, Short> orderMap = new HashMap<>(); // 避免重复查询订单数据
        for (MjUserOrderStatus userOrderStatus : userOrderStatusList){
            if (orderMap.containsKey(userOrderStatus.getOrderId())){
                Short orderStatus = orderMap.get(userOrderStatus.getOrderId());
                if (orderStatus == 7){
                    // 已完成的状态，把渠道商对应的状态改成已结束
                    mjUserOrderStatusMapper.updateOrderStatusById(userOrderStatus.getId(), 77);
                }
            }else {
                MjOrder order = orderMapper.selectByPrimaryKey(userOrderStatus.getOrderId());
                orderMap.put(userOrderStatus.getOrderId(), order.getStatus());
                if (order.getStatus() == 7){
                    // 已完成的状态，把渠道商对应的状态改成已结束
                    mjUserOrderStatusMapper.updateOrderStatusById(userOrderStatus.getId(), 77);
                }
            }
        }
    }

}
